﻿@using NetCoreCMS.Framework.Utility
@using NetCoreCMS.Framework.Modules
@using System.Linq;

@{
    Layout = Constants.AdminLayoutName;
    var ControllerName = "CmsWidget";
}

<style>
    .ncc-widget-box-container .ncc-widget-box {
        width:48%;
        float:left;
        margin-right: 2%;
    }
    .widget-container {
        height: 75vh;
    }
    .widget-layout-container {
        height: 70vh;
    }
    .fullHeight{
        overflow-x: hidden;
        overflow-y: auto;
    }
    a:hover{
        text-decoration:none;
    }
    .up {
        cursor: pointer;
        font-weight: bold;
        font-size: 30px;
        margin: -10px 5px 10px 5px;
        color: #5cb85c;
    }
    .down {
        cursor: pointer;
        font-weight: bold;
        font-size: 30px;
        margin: -10px 5px 10px 5px;
        color: #eea236;
    }
    .remove {
        cursor: pointer;
        font-weight: bold;
        font-size: 22px;
        margin: -5px 5px 10px 5px;
        color: #d9534f;
    }

</style>

<div class="">

    <div class="row">
        <div class="col-lg-7">
            <div id="ncc-module-widget-box-container" class="panel panel-default" ondrop="dropBack(event)" ondragover="allowDrop(event)">
                <div class="panel-heading">
                    Widgets
                </div>
                <div class="panel-body ncc-widget-box-container">
                    <div class="fullHeight widget-container">
                        @foreach (IModule item in ViewBag.Modules)
                        {
                            if (item.Widgets.Count > 0)
                            {
                                @*<div class="col-md-6">
                                    <div class="panel panel-primary">
                                        <div class="panel-heading">@item.ModuleTitle</div>
                                        <div id="Container_@item.ModuleId" data-module-id="@item.ModuleId"  class="panel-body"  ondrop="dropBack(event)" ondragover="allowDrop(event)">*@
                                            @foreach (Widget widget in item.Widgets)
                                            {   <div id="@Guid.NewGuid().ToString()" class="ncc-widget-box" data-widget-id="@widget.WidgetId" data-module-id="@item.ModuleName"  draggable="true" ondragstart="drag(event)">                                     
                                                    <div class="panel panel-default" >
                                                        <div class="panel-heading">
                                                            <i class="glyphicon glyphicon-move margin-right-10"></i>&nbsp;
                                                            <a draggable="false" data-toggle="collapse" href="#collapse_@widget.WidgetId.Replace('.', '_')">
                                                                @widget.Title.Replace("Widget", "") (@item.ModuleTitle.Replace("NetCoreCMS", "").Replace("Module", "").Trim())
                                                            </a>
                                                        </div>
                                                        <div id="collapse_@widget.WidgetId.Replace('.', '_')" class="panel-collapse collapse">
                                                            <div class="panel-body">
                                                                @widget.Description
                                                            </div>
                                                        </div>
                                                    </div>                    
                                                </div>
                                            }
                                        @*</div>
                                    </div>
                                </div>*@
                            }
                        }

                        @if (ViewBag.Theme != null && ViewBag.Theme.Widgets.Count > 0)
                        {
                            foreach (Widget widget in ViewBag.Theme.Widgets)
                            {   
                                <div id="@Guid.NewGuid().ToString()" class="ncc-widget-box" data-widget-id="@widget.WidgetId" data-theme-id="@ViewBag.Theme.ThemeId" draggable="true" ondragstart="drag(event)">
                                    <div class="panel panel-default">
                                        <div class="panel-heading">
                                            <i class="glyphicon glyphicon-move margin-right-10"></i>&nbsp;
                                            <a draggable="false" data-toggle="collapse" href="#collapse_@widget.WidgetId.Replace('.', '_')">
                                                @widget.Title.Replace("Widget", "") (@ViewBag.Theme.ThemeName.Replace("NetCoreCMS", "").Replace("Theme", "").Trim())
                                            </a>
                                        </div>
                                        <div id="collapse_@widget.WidgetId.Replace('.', '_')" class="panel-collapse collapse">
                                            <div class="panel-body">
                                                @widget.Description
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            }
                        }
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="panel with-nav-tabs panel-default">
                <div class="panel-heading">
                    Layout Zones
                </div>
                <div class="panel-body">
                    <div class="row">
                        <ul class="nav nav-tabs">
                            @{
                                var active = "active";
                                var ariaExpanded = "aria-expanded=\"true\"";
                            }
                            @foreach (var layout in ThemeHelper.ActiveTheme.Layouts)
                            {
                                if (!string.IsNullOrEmpty(ViewBag.sLayout))
                                {
                                    if (layout.Name == ViewBag.sLayout) { active = "active"; }
                                    else { active = ""; }
                                }
                                var tabName = "#tab_" + layout.Name.Replace(' ', '_');

                                    <li class="@active">
                                        @*<a href="@tabName" data-toggle="tab" @ariaExpanded> @layout.Name.Replace("Layout", "") </a>*@
                                        <a asp-controller="@ControllerName" asp-action="Index" asp-route-sLayout="@layout.Name" @ariaExpanded> @layout.Name.Replace("Layout", "") </a>
                                    </li>

                                active = "";
                                ariaExpanded = "";
                            }
                        </ul>
                        <div class="tab-content fullHeight widget-layout-container">
                            @{
                                active = "active";
                            }
                            @foreach (var layout in ThemeHelper.ActiveTheme.Layouts)
                            {
                                if (!string.IsNullOrEmpty(ViewBag.sLayout))
                                {
                                    if (layout.Name == ViewBag.sLayout) { active = "active"; }
                                    else { active = ""; }
                                }
                                var tabName = "tab_" + layout.Name.Replace(' ','_');
                                <div class="tab-pane @active" id="@tabName">
                                    <div class="col-md-12">
                                        <div class="text-right">Widget Sections for layout <strong>@layout.Name </strong> </div>
                                        @foreach (var zone in layout.LayoutZones)
                                        {
                                            <div class="panel panel-default">
                                                <div class="panel-heading">
                                                    @zone
                                                </div>
                                                <div style="color:#cccccc; padding:10px 10px;">Drop widget below.</div>
                                                <div data-theme-id="@ThemeHelper.ActiveTheme.ThemeId" data-layout-name="@layout.Name" data-layout-zone="@zone" class="panel-body" ondrop="drop(event)" ondragover="allowDrop(event)"  style="border:2px dashed #AAA; min-height:70px;" >                                            
                                                     @{ 
                                                         var wZones = ((List<NccWebSiteWidget>)ViewBag.WebsiteWidgetZones).Where(x => x.Zone == zone && x.LayoutName == layout.Name).OrderBy(x=>x.WidgetOrder).ToList();
                                                         
                                                         var widgetInZontSerial = 0;
                                                         foreach (var wZone in wZones) {
                                                             widgetInZontSerial++;
                                                             var wList = new List<Widget>();
                                                             foreach (var x in (List<NetCoreCMS.Framework.Modules.IModule>)ViewBag.Modules) {
                                                                 wList.AddRange(x.Widgets);
                                                             }
                                                             if(ThemeHelper.ActiveTheme.Widgets != null && ThemeHelper.ActiveTheme.Widgets.Count > 0)
                                                             {
                                                                 wList.AddRange(ThemeHelper.ActiveTheme.Widgets);
                                                             }
                                                             var w = wList.Where(x => x.WidgetId == wZone.WidgetId).FirstOrDefault();
                                                             if (w != null) {
                                                                 w.Init(wZone.Id, true);
                                                                 var panelId = Guid.NewGuid().ToString();
                                                                 <div id="@panelId" data-website-widget-id="@wZone.Id" data-widget-id="@wZone.WidgetId" data-module-id="@wZone.ModuleName" data-theme-id="@wZone.ThemeId"  data-layout-name="@wZone.LayoutName" data-layout-zone="@wZone.Zone"   ondragstart="drag(event)">
                                                                    <div class="panel panel-default"  >
                                                                        <div class="panel-heading">
                                                                            <i class="glyphicon glyphicon-move margin-right-10"></i>&nbsp;
                                                                            <a draggable="false" data-toggle="collapse" href="#collapse_@wZone.Id">
                                                                                @*@wZone.WidgetOrder*@
                                                                                @w.Title @{
                                                                                        var lang = "";
                                                                                        if (GlobalContext.WebSite.IsMultiLangual)
                                                                                        {
                                                                                            lang = string.IsNullOrEmpty(w.Language) ? " ( All )" : " ( " + w.Language + " )";
                                                                                        }
                                                                                    }
                                                                                @lang
                                                                            </a>
                                                                            <a class="pull-right remove" onclick="RemoveWebSiteZoneWidget('@panelId')" title="Delete Widget"><i class="fa fa-times"></i></a>
                                                                            @if (wZones.Count > 1)
                                                                            {
                                                                                    @if (widgetInZontSerial > 1)
                                                                                    {
                                                                                        <a class="pull-right up" onclick="UpWebSiteZoneWidget(@wZone.Id,@wZone.WidgetOrder,'@layout.Name')" title="Up"><i class="fa fa-caret-up"></i></a>
                                                                                    }
                                                                                    @if (widgetInZontSerial < wZones.Count)
                                                                                    {
                                                                                        <a class="pull-right down" onclick="DownWebSiteZoneWidget(@wZone.Id,@wZone.WidgetOrder,'@layout.Name')" title="Down"><i class="fa fa-caret-down"></i></a>
                                                                                    }
                                                                            }
                                                                        </div>
                                                                        <div id="collapse_@wZone.Id" class="panel-collapse collapse">
                                                                            <div class="panel-body">
                                                                                 @*@w.Description*@
                                                                                @Html.Raw(w.RenderConfig())
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            }
                                                        }
                                                    }
                                                </div>
                                            </div>
                                        }
                                    </div>
                                </div>

                                active = "";
                            }
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>
<div id="ncc-widget-treash" style="width:1px;height:1px;"></div>

<script>
    function allowDrop(ev) {
        ev.preventDefault();
    }

    function drag(ev) {
        ev.dataTransfer.setData("widgetId", ev.target.id);
    }

    function drop(ev) {

        //console.log("Drop");
        ev.preventDefault();
        var targetDiv = ev.target;

        var divId = ev.dataTransfer.getData("widgetId");
        var div = document.getElementById(divId);
        targetDiv.appendChild(div);
        var clonedDiv = $(div).clone();
        var uid = GUID.NewGUID();
        $(clonedDiv).attr("id", uid);
        //clonedDiv.appendTo(targetDiv);
        //$(div).clone().appendTo("#ncc-module-widget-box-container");

        var moduleId = $(div).attr("data-module-id");
        var zone = $(targetDiv).attr("data-layout-zone");
        var layout = $(targetDiv).attr("data-layout-name");
        var theme = $(targetDiv).attr("data-theme-id");
        var widgetId = $(div).attr("data-widget-id");

        $(clonedDiv).attr("data-theme-id", theme);
        $(clonedDiv).attr("data-layout-name", layout);
        $(clonedDiv).attr("data-layout-zone", zone);

        NccPageMask.ShowLoadingMask();
        $.ajax({
            method: 'POST',
            url: '/CmsWidget/SaveZoneWidget',
            data: { module: moduleId, theme: theme, layout: layout, zone: zone, widget: widgetId },
            success: function (rsp) {
                NccPageMask.HideLoadingMask();
                console.log(rsp);
                NccGlobalAlert.ShowSuccess(rsp.message);
                $(clonedDiv).attr("data-website-widget-id", rsp.data.id);
                setTimeout(function () {
                    //window.location.reload(1);
                    window.location.href = window.location.pathname + "?sLayout=" + layout;
                }, 500);
            },
            error: function (rsp) {
                NccPageMask.HideLoadingMask();
                NccGlobalAlert.ShowError("Error occoured. Please try again after refresh the page.");
            }
        });
    }
     
    function UpWebSiteZoneWidget(websiteWidgetId, oldOrder, layout) {
        $.ajax({
            method: 'POST',
            url: '/CmsWidget/UpdateWebsiteWidgetOrder',
            data: { webSiteWidgetId: websiteWidgetId, oldOrder: oldOrder , operation:'up'},
            success: function (rsp) {       
                NccGlobalAlert.ShowSuccess(rsp.message);
                //setTimeout(function () {
                //    //window.location.reload(1);
                //    //window.location.href = window.location.pathname + "?sLayout=" + layout;
                //}, 500);
            },
            error: function (rsp) {
                NccGlobalAlert.ShowError("Error occoured. Please try again after refresh the page.");
            }
        });
    }

    function DownWebSiteZoneWidget(websiteWidgetId, oldOrder, layout) {
        $.ajax({
            method: 'POST',
            url: '/CmsWidget/UpdateWebsiteWidgetOrder',
            data: { webSiteWidgetId: websiteWidgetId, oldOrder: oldOrder, operation: 'down' },
            success: function (rsp) {
                NccGlobalAlert.ShowSuccess(rsp.message);
                //setTimeout(function () {
                //    //window.location.reload(1);
                //    //window.location.href = window.location.pathname + "?sLayout=" + layout;
                //}, 300);
            },
            error: function (rsp) {
                NccGlobalAlert.ShowError("Error occoured. Please try again after refresh the page.");
            }
        });
    }

    function RemoveWebSiteZoneWidget(panelId) {

        NccPageMask.ShowLoadingMask();
        var wZoneId = $("#" + panelId).attr("data-website-widget-id");
        $.ajax({
            method: 'POST',
            url: '/CmsWidget/RemoveZoneWidgetById',
            data: { zoneWidgetId: wZoneId },
            success: function (rsp) {
                NccPageMask.HideLoadingMask();
                //console.log(rsp);
                NccGlobalAlert.ShowSuccess(rsp.message);
                $("#" + panelId).remove();
            },
            error: function (rsp) {
                NccPageMask.HideLoadingMask();
                NccGlobalAlert.ShowError("Error occoured. Please try again after refresh the page.");
            }
        });
    }

    function removeWidget(moduleId, theme, layout, zone, widgetId) {
        NccPageMask.ShowLoadingMask();
        $.ajax({
            method: 'POST',
            url: '/CmsWidget/RemoveZoneWidget',
            data: { module: moduleId, theme: theme, layout: layout, zone: zone, widget: widgetId },
            success: function (rsp) {
                NccPageMask.HideLoadingMask();
                console.log(rsp);
                NccGlobalAlert.ShowSuccess(rsp.message);
            },
            error: function (rsp) {
                NccPageMask.HideLoadingMask();
                NccGlobalAlert.ShowError("Error occoured. Please try again after refresh the page.");
            }
        });
    }

    function dropBack(ev) {
        console.log("Drop back");

        ev.preventDefault();
        var targetDiv = ev.target;
        var divId = ev.dataTransfer.getData("widgetId");

        console.log(divId);

        var div = document.getElementById(divId);
        console.log(div);

        var zone = $(div).attr("data-layout-zone");
        var layout = $(div).attr("data-layout-name");
        var theme = $(div).attr("data-theme-id");
        var widgetId = $(div).attr("data-widget-id");
        var srcModuleId = $(div).attr("data-module-id");

        console.log(zone, layout, theme, widgetId, srcModuleId);
        removeWidget(srcModuleId, theme, layout, zone, widgetId);

        $("#ncc-widget-treash").append(div).empty();


    }

</script>